//
//  JFBOrderDetailDS.m
//  ios-supplier
//
//  Created by feynmanyuan on 15/4/16.
//  Copyright (c) 2015年 feynmanyuan. All rights reserved.
//

#import "JFBMerchandiseDS.h"
/*
 //商品ID
 @property (nonatomic, assign) NSUInteger mpId;
 // 商品名称
 @property (nonatomic, strong) NSString *name;
 // 单位
 @property (nonatomic, strong) NSString *calculationUnit;
 // 商品状态，是否上架  4：上架  5：下架  -1：全部
 @property (nonatomic, assign) NSUInteger mpStatus;
 // 库存量
 @property (nonatomic, assign) NSInteger stockNum;
 //销售类型   3：本来精选4：通货
 @property (nonatomic, assign) NSUInteger saleType;
 // 商品图片
 @property (nonatomic, strong) NSString *mpURL;
 // 市场价格
 @property (nonatomic, strong) NSDecimalNumber *marketPrice;
 // 门店价格
 @property (nonatomic, strong) NSDecimalNumber *storePrice;//
 // 重量
 @property (nonatomic, strong) NSString *weight;
 */
@implementation JFBMerchandiseDS
- (instancetype)initWithAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    self.mpId = [[attributes objectForKey:@"mpId"] isEqual:[NSNull null]] ? 0 : [[attributes objectForKey:@"mpId"] intValue];
    
    self.name = [[attributes objectForKey:@"name"] isEqual:[NSNull null]] ? 0 : [attributes objectForKey:@"name"];
    
    self.marketPrice = [NSString formatDecimal:[[attributes objectForKey:@"marketPrice"] isEqual:[NSNull null]] ? [[NSDecimalNumber alloc] initWithInt: 0] : [attributes objectForKey:@"marketPrice"]];
    self.storePrice = [[attributes objectForKey: @"storePrice"] isEqual: [NSNull null]] ? self.marketPrice : [attributes objectForKey: @"storePrice"];
    
//    self.mpURL = ImageDefaultPlaceholder;
    self.calculationUnit = [[attributes objectForKey:@"calculationUnit"] isEqual:[NSNull null]] ? 0 : [attributes objectForKey:@"calculationUnit"];
    
    self.standard = [[attributes objectForKey:@"standard"] isEqual:[NSNull null]] ? 0 : [attributes objectForKey:@"standard"];
    
    self.mpStatus = [[attributes objectForKey:@"mpStatus"] isEqual:[NSNull null]] ? 0 : [[attributes objectForKey:@"mpStatus"] intValue];
    
    self.saleType = [[attributes objectForKey: @"saleType"] isEqual: [NSNull null]] ? 0 :  [[attributes objectForKey:@"saleType"] intValue];
    
    self.stockNum = [[attributes objectForKey: @"stockNum"] isEqual: [NSNull null]] ? 0 :  [[attributes objectForKey:@"stockNum"] intValue];
    self.total = [[attributes objectForKey: @"total"] isEqual: [NSNull null]] ? 0 : [[attributes objectForKey: @"total"]  integerValue];
    self.shelvesNum = [[attributes objectForKey: @"shelvesNum"] isEqual: [NSNull null]] ? 0 : [[attributes objectForKey: @"shelvesNum"]  integerValue];
    self.pullOffShelvesNum = [[attributes objectForKey:@"pullOffShelvesNum"] isEqual:[NSNull null]]?0:[[attributes objectForKey:@"pullOffShelvesNum"] integerValue];
    return self;
}

- (instancetype)initWithOrderListAttributes:(NSDictionary *)attributes {
    self = [super init];
    if (!self) {
        return nil;
    }
    
    self.mpId = [[attributes objectForKey:@"mpId"] intValue];
    self.name = [attributes objectForKey:@"name"];
    ;
    NSString * storePrice = [[attributes objectForKey:@"storePrice"] isEqual:[NSNull null]] ? @"0" : [[attributes objectForKey:@"storePrice"] stringValue];
    self.storePrice = [NSDecimalNumber decimalNumberWithString:storePrice];
    
    NSString * marketPrice = [[attributes objectForKey:@"marketPrice"] isEqual:[NSNull null]] ? @"0" : [[attributes objectForKey:@"marketPrice"] stringValue];
    
    self.marketPrice = [NSDecimalNumber decimalNumberWithString:marketPrice];
    self.mpURL = ImageDefaultPlaceholder;
    self.calculationUnit = @"";
    self.standard = @"";
    self.mpStatus = true;
   
    return self;
}
+ (NSDictionary *)modelCustomPropertyMapper{
    return @{
             @"ID" : @"mpId"
             };
}
///============================扩展属性=================================


///====================================================================

//加载二级类目下的详细商品列表
+ (NSURLSessionDataTask *)loadMerchandiseList:(void (^)(NSArray *merchandiseList, NSError *error))block categoryId:(NSUInteger)categoryId  ut:(NSString *)ut pager:(JFBPager*)pager{
    
    NSDictionary *parameter = @{@"categoryId":[NSNumber numberWithInteger:categoryId],@"ut":[[NSUserDefaults standardUserDefaults]objectForKey:@"ut"]};
    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/getMerchantProductList.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
//            NSMutableArray *result = [@[] mutableCopy];
            NSDictionary *data = [JSON valueForKey:@"data"];
            
            NSArray *response = [data valueForKeyPath:@"merchantProductList"];
//            for( NSDictionary *merchandise in response ) {
//                [result addObject:[[JFBMerchandiseDS alloc] initWithAttributes:merchandise]];
//            }
            
            block([NSArray yy_modelArrayWithClass:[JFBMerchandiseDS class] json:response], nil);
            
        }else if ([JSON[@"code"] integerValue] == 99){
            UIViewController* viewController;
            UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
            viewController = [mainStoryBoard instantiateViewControllerWithIdentifier:@"Login"];
        }
        else {
            block(nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(nil, error);
    }];
}

//调整商品上下架----之前做了判断商品是否为本来精选
+ (NSURLSessionDataTask *)switchUpAndDownShelf:(void (^)(BOOL isSuccess, NSError *error))block merchandiseID:(NSUInteger)merchandiseID oldStatus:(NSInteger)oldStatus newStatus:(NSInteger)newStatus saleType:(NSInteger)saleType{
    NSDictionary *parameter = @{@"mpId":[NSNumber numberWithInteger:merchandiseID], @"oldStatus":[NSNumber numberWithInteger:oldStatus]
                                , @"newStatus":[NSNumber numberWithInteger:newStatus]
                                , @"saleType":[NSNumber numberWithInteger:saleType]
                                };
    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/updateMerProdStatus.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            NSLog(@"......................................单独点击商品的上下架");
            block(true, nil);
        } else {
            block(false, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, error);
    }];
}

////调整商品上下架----之前做了判断商品是否为本来精选
//+ (NSURLSessionDataTask *)switchUpAndDownShelf:(void (^)(BOOL isSuccess, NSError *error))block merchandiseID:(NSUInteger)merchandiseID status:(NSUInteger)status{
//    NSDictionary *parameter = @{@"product_id":[NSNumber numberWithInteger:merchandiseID], @"status":[NSNumber numberWithInteger:status]};
//    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/updateMerProdStatus.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
//        NSObject * error = [JSON valueForKey:@"code"];
//        if( [error isEqual: @"0"] ) {
//            NSLog(@"......................................单独点击商品的上下架");
//            block(true, nil);
//        } else {
//            block(false, nil);
//        }
//    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
//        block(false, error);
//    }];
//}

+ (NSURLSessionDataTask *)batchUpAndDownShelf:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block productIds:(NSString*)productIds optFlag:(NSUInteger)optFlag{
    
    NSDictionary *parameter = @{@"product_ids":productIds, @"opt_flag":[NSNumber numberWithInteger:optFlag]};
    return [[JFBAPIClient sharedClient:true] GET:@"/shop/product/bat_on_off_line.json" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            block(true, @"操作成功", nil);
        } else {
            block(false, @"操作失败", nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"操作失败，请稍候重试", error);
    }];
    return nil;
}


//上下架 修改价格
+ (NSURLSessionDataTask *)changeUnitPrice:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block merchandiseID:(NSUInteger)merchandiseID price:(NSDecimalNumber*)price status:(NSUInteger)status{
    
    NSDictionary *parameter = @{@"merchandiseID":[NSNumber numberWithInteger:merchandiseID], @"product_price":price, @"status":[NSNumber numberWithInteger:status]};
    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/updateMerProdStatus.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            block(true, @"修改成功", nil);
        } else {
            block(false, @"修改失败", nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"修改失败", error);
    }];
    return nil;
}
#pragma mark -点击保存调用接口
/*
 mpId         商品ID
 realStockNum 实际库存量
 addstockNum  增加库存量
 storePrice   门店价格
 */
//
+ (NSURLSessionDataTask *)changeUnitPrice:(void (^)(BOOL isSuccess, NSString *message, NSError *error))block  mpId:(NSUInteger)mpId realStockNum:(NSUInteger)realStockNum addstockNum:(NSDecimalNumber*)addstockNum storePrice:(NSDecimalNumber*)storePrice oldStatus:(NSInteger)oldStatus newStatus:(NSInteger)newStatus saleType:(NSInteger)saleType{
    
    NSDictionary *parameter = @{
                                @"mpId":[NSNumber numberWithInteger:mpId],
                                @"realStockNum":[NSNumber numberWithInteger:realStockNum],
                                @"addstockNum":addstockNum,
                                @"storePrice":storePrice,
                                @"oldStatus":@(oldStatus),
                                @"newStatus":@(newStatus),
                                @"saleType":@(saleType)
                                };
    
    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/updateMerchantProduct.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            block(true, @"修改成功", nil);
        } else {
            block(false, @"修改失败", nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(false, @"修改失败", error);
    }];
    return nil;
}

+ (NSURLSessionDataTask *)scanQuery:(void (^)(JFBMerchandiseDS *merchandise, NSError *error))block code:(NSString*)code {
    
    NSDictionary *parameter = @{@"code":code};
    return [[JFBAPIClient sharedClient:true] GET:@"/shop/product/code.json" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {
        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            NSArray *response = [JSON valueForKeyPath:@"data"];
            if( response.count >= 1 ) {
                JFBMerchandiseDS * merchandise = [[JFBMerchandiseDS alloc] initWithAttributes:[response objectAtIndex:0]];
                block(merchandise, nil);
            }else {
                block(nil, nil);
            }
        } else {
            block(nil, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(nil, error);
    }];
    
    return nil;
}

//搜索商品
+ (NSURLSessionDataTask *)search:(void (^)(NSArray *merchandiseList, NSUInteger onlineCount, NSUInteger offlineCount,  NSError *error))block name:(NSString*)name showType:(NSUInteger)showType{
    
    NSDictionary *parameter = @{@"key_str":name, @"show_type":[NSNumber numberWithInteger:showType]};
    
    return [[JFBAPIClient sharedClient:true] GET:@"/back-product/getMerchantProductList.do" parameters:parameter success:^(NSURLSessionDataTask * __unused task, id JSON) {

        NSObject * error = [JSON valueForKey:@"code"];
        if( [error isEqual: @"0"] ) {
            NSMutableArray *result = [@[] mutableCopy];
            NSArray *response = [JSON valueForKeyPath:@"data"][@"merchantProductList"];
            NSDictionary *searchResult = [JSON valueForKeyPath:@"dataReserve1"];
            if( ![response isEqual:[NSNull null]] ) {
                for( NSDictionary *merchandise in response ) {
                    NSMutableDictionary * dict = [merchandise mutableCopy];
                    
                    [dict setObject:[NSString stringWithFormat:@"%@%@", [dict objectForKey:@"weight"], [dict objectForKey:@"weight_name"]] forKey:@"buy_quantity"];
                    [result addObject:[[JFBMerchandiseDS alloc] initWithAttributes:dict]];
                }
            }
            block([NSArray arrayWithArray:result], [[searchResult valueForKey:@"shelvesNum"] integerValue], [[searchResult valueForKey:@"total"] integerValue], nil);
        } else {
            block(nil, 0, 0, nil);
        }
    } failure:^(NSURLSessionDataTask *__unused task, NSError *error) {
        block(nil, 0, 0, error);
    }];
    
    return nil;
}


@end
